<template>
  <div class="upload-wrap">
    <div class="file-wrap" v-if="fileArray && fileArray.length > 0">
      <n-button
        v-for="(item, i) in fileArray"
        :key="i"
        @click="fileTap(item.url)"
        icon-placement="right"
      >
        <template #icon v-if="!currentDisabled">
          <n-icon :size="16" @click.stop="deleteTap(i)">
            <CloseOutlined />
          </n-icon>
        </template>
        {{ item.name }}
      </n-button>
    </div>
    <n-upload
      v-if="!currentDisabled"
      :action="`${apiUrl}/upload`"
      :headers="uploadHeaders"
      @finish="handleLetterGuaranteeFinish"
      :show-file-list="false"
      :disabled="currentDisabled || fileArray.length >= limit"
    >
      <n-button type="primary" ghost size="small">
        {{ fileArray.length >= limit ? '文件数量已达限制' : '上传文件' }}
      </n-button>
    </n-upload>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, inject, computed } from 'vue';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUser } from '@/store/modules/user';
  import { CloseOutlined } from '@vicons/antd';

  const userStore = useUser();
  const globSetting = useGlobSetting();
  const { apiUrl } = globSetting;
  const uploadHeaders = {
    Authorization: userStore.getToken,
  };

  const emit = defineEmits(['update:modelValue']);

  const props = defineProps({
    modelValue: {
      type: Array,
      default: () => [],
    },
    // 允许上传文件的最大数量
    limit: {
      type: Number,
      default: 3,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 文件最大10MB
    maxSize: {
      type: Number,
      default: 10,
    },
  });
  const nForm: any = inject('n-form'); // 使用inject函数注入属性
  const currentDisabled = computed(() => {
    return props.disabled || (nForm?.props?.disabled ?? false);
  });
  const fileArray = ref<any[]>([]);
  watch(
    () => props.modelValue as string[],
    (newVal: string[]) => {
      fileArray.value = props.modelValue as string[];
    },
    { deep: true, immediate: true }
  );
  const handleLetterGuaranteeFinish = ({ file, event }) => {
    const res = JSON.parse((event?.target as XMLHttpRequest).response);
    fileArray.value.push({
      name: file.name,
      url: res.data,
    });
    emit('update:modelValue', fileArray.value);
    return file;
  };
  function previewTap(url) {
    window.open(url);
  }
  function deleteTap(i) {
    fileArray.value.splice(i, 1);
    emit('update:modelValue', fileArray.value);
  }
  const fileTap = (url) => {
    window.open(url, '_blank');
  };
</script>

<style scoped lang="less">
  .file-wrap {
    margin-bottom: 10px;

    .n-tag {
      margin-right: 10px;
    }

    .n-button {
      margin-right: 10px;
    }
  }
</style>
